package com.endurance.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class Test06FileUploadController {

    @GetMapping("/upload")
    public String jump() throws IOException {
        return "upload";
    }

    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile uploadFile, HttpServletRequest httpServletRequest) throws IOException {

        // 1. 获取上传文件的名称,做非空判断
        String originalFilename = uploadFile.getOriginalFilename();
        if (uploadFile != null && !StringUtils.isEmpty(originalFilename)) {
            // 2. 解决上传文件重名的问题：将文件名替换成UUID，保证文件名唯一
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 3. 获取源文件扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 4. 将uuid值和扩展名拼接获得唯一文件名
            String newFileName = uuid + extension;
            // 5. 将上传的文件写入到服务端硬盘
            uploadFile.transferTo(new File(httpServletRequest.getServletContext().getRealPath("/"), newFileName));
        }
        return "success";
    }




}
